package com.zhiyou100.util;

import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

public class RedisUtil {
	private Logger logger = Logger.getLogger(RedisUtil.class);
	private RedisTemplate<Serializable, Object> redisTemplate;
	public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
	
	//根据键删除缓存
	public boolean delete(String key){
		boolean flag = false;
		try{
			redisTemplate.delete(key);
			flag=true;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("删除缓存失败.....");
		}
		return flag;
	}
	//批量删除
	public void remove(String...keys){
		for(String key:keys){
			delete(key);
		}
	}
	//判断键是否存在
	public boolean exists(String key){
		return redisTemplate.hasKey(key);
	}
	//存储缓存
	public boolean set(String key,Object value){
		boolean flag = false;
		try{
			ValueOperations<Serializable, Object> operation = redisTemplate.opsForValue();
			operation.set(key, value);
			flag = true;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("存入缓存失败......");
		}
		
		return flag;
	}
	//存储缓存设置过期时间
	public boolean set(String key,Object value,long times){
		boolean flag = false;
		try{
			ValueOperations<Serializable, Object> operation = redisTemplate.opsForValue();
			operation.set(key, value);
			//设置过期时间
			redisTemplate.expire(key, times, TimeUnit.SECONDS);
			flag = true;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("存入缓存失败......");
		}
		return flag;
	}
	//查询缓存
	public Object get(String key){
		ValueOperations<Serializable, Object> operation=redisTemplate.opsForValue();
		return operation.get(key);
	}
	
	//清除所有缓存
	public void flushCache(){
		Set keys=redisTemplate.keys("*");
		for (Object key : keys) {
			delete((String)key);
		}
	}
	
	
}
